﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.MesMsgQueues;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Service.Common;
using System;
using System.Xml;

namespace HamcoWcs.Service.Mes.Parsers
{
    public class MesMsgParser_ChangeMachinePalletTypeRequest : MesMsgParserBase
    {
        public override string EventName => "CHANGEMACHINEPALLETTYPEREQUEST";

        private readonly IPconBaseService _pconBaseService;

        public MesMsgParser_ChangeMachinePalletTypeRequest(IPconBaseService pconBaseService, ILoggerService loggerService, WcsDbContext wcsDbContext, IMapper mapper) : base(loggerService, wcsDbContext, mapper)
        {
            _pconBaseService = pconBaseService;
        }

        public override void HandleEvent(MesMsgQueue message)
        {
            string code = XmlHelper.GetXPathText(message.Return, "//RETURNCODE");
            string machineNmae = XmlHelper.GetXPathText(message.Return, "//MACHINENAME");
            var pcon = _pconBaseService.GetPcon(machineNmae, "02");
            if (pcon == null) throw new Exception($"未找到pcon:{machineNmae}-02");

            var pconSendMsg = new PconSendMsg()
            {
                PconName = (ushort)pcon.PconName,
            };

            if (code == "0")
            {
                string type = XmlHelper.GetXPathText(message.Return, "//PALLETTYPE").ToUpper();
                switch (type)
                {
                    case "FULL": pconSendMsg.Request = 8; break;
                    case "EMPTYBOX": pconSendMsg.Request = 8; break;
                    case "PALLET": pconSendMsg.Request = 8; break;
                    default:
                        message.Status = (int)EnumMesMsgStatus.Error;
                        throw new Exception("Unknow pallet type");
                }
            }
            else
            {
                pconSendMsg.ErrorCode = 10;
                pconSendMsg.Request = 9;
            }

            InsertDeviceMsgInQueue(pcon, pconSendMsg);
            message.Status = (int)EnumMesMsgStatus.Completed;
        }
    }
}
